from django import template
from datetime import datetime
from datetime import timedelta
from datetime import date
from ..models import product as p
import random
import pytz

register = template.Library()

# 商品过期时间计算
@register.filter
def timediff(storage):
    # TODO 在确定了数据模型后需要更改变量获取方式
    reserve_day = storage.p_ID.p_expiration
    td = datetime.today() - datetime.strptime(str(storage.product_date), "%Y-%m-%d") - timedelta(days=reserve_day)
    diff_day = td.days
    diff_hour = td.seconds // 3600
    return "%d天%d小时" % (diff_day, diff_hour)


# 订单已获得时间记录
@register.filter
def time_distance(order):
    try:
        td = datetime.today().replace(tzinfo=pytz.timezone("UTC")) - order.start_time
        diff_day = td.days
        diff_hour = td.seconds //3600
    # print(order.start_time)
    # print(diff_day)
    # print(diff_hour)
        return "%d天%d小时" % (diff_day, diff_hour)
    except:
        return None


@register.filter
def random_temperature(i):
    return random.randint(2,10)